package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.team;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.business.EFuncModelShowState;
import com.gzhryc.shared_device.oem.code.config.dao.db.FuncModel;
import com.gzhryc.shared_device.oem.code.config.dao.enums.FuncModelEnum;
import com.gzhryc.shared_device.oem.code.config.services.FuncModelService;
import com.gzhryc.shared_device.oem.code.place.dao.db.Clerk;
import com.gzhryc.shared_device.oem.code.place.dao.db.ClerkFuncModel;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceClerk;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.enums.ClerkFuncModelEnum;
import com.gzhryc.shared_device.oem.code.place.dao.models.ClerkPlaceCount;
import com.gzhryc.shared_device.oem.code.place.services.ClerkFuncModelService;
import com.gzhryc.shared_device.oem.code.place.services.ClerkService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceClerkService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.ClerkSearch;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.ELoginUserRoleType;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserAddRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserFuncModelListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserFuncModelListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserFuncModelUpdateRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserPlaceListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserPlaceListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.ClerkUserPowerUpdateRequest;

public class ClerkUserController {

	@Route(value = "/agent/api/v1/merchant/clerk/list.data")
	public ClerkUserListResponse list(HttpServletRequest request) {
		ClerkUserListResponse apiResp = new ClerkUserListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
		ClerkUserListRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserListRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if(loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();

                ClerkSearch search = new ClerkSearch();
                search.setMerchantUserId(loginUser.getId());
                search.setTrim(apiReq.getBody().getTrim());

                List<Clerk> clerkList = ClerkService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                if (clerkList != null && clerkList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    List<Long> userIds = new ArrayList<>();
                    for (Clerk clerk : clerkList) {
                    	userIds.add(clerk.getUserId());
                    }

                    List<ClerkPlaceCount> placeCountList = PlaceClerkService.self().findPlaceCountByUserKeys(loginUser.getId(),userIds);
                    
                    for (Clerk clerk : clerkList) {
                    	ClerkUserListResponse.Item item = new ClerkUserListResponse.Item();
                        item.setUserId(clerk.getUserId());
                        item.setUserName(clerk.getUser().getName());
                        item.setUserPhone(clerk.getUser().getPhone());
                        item.setNote(clerk.getNote());
                        item.setLastLoginDate(clerk.getLastLoginDate());
                        item.setCreateDate(clerk.getCreateDate());
                        item.setPlaceCount(0);
                        if(placeCountList != null && placeCountList.size() > 0){
                            for(ClerkPlaceCount placeCount : placeCountList){
                                if(placeCount.getUserId().equals(item.getUserId())){
                                    if(placeCount.getPlaceCount() != null) {
                                        item.setPlaceCount(placeCount.getPlaceCount().intValue());
                                    }
                                    break;
                                }
                            }
                        }
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/merchant/clerk/add.do")
    public DefaultAPIResponse add(HttpServletRequest request){
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"新增失败");
        ClerkUserAddRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserAddRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getPhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                if(!ValidateTools.isPhone(apiReq.getBody().getPhone())){
                    apiResp.setMsg("手机号不正确，请检查");
                    return apiResp;
                }

                User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                Long userId = apiReq.getBody().getUserId();
                if(userId != null){
                    if(user == null || !user.getId().equals(userId)){
                        apiResp.setMsg("未找到用户信息");
                        return apiResp;
                    }

                    Clerk clerk = new Clerk();
                    clerk.setUserId(userId);
                    clerk.setMerchantUserId(loginUser.getId());
                    clerk.setNote(apiReq.getBody().getNote());

                    try {
                        if(ClerkService.self().add(clerk)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
                    if(user != null){
                        apiResp.setMsg("用户已存在，请重新上一步");
                        return apiResp;
                    }else {
                        if(StringTools.isBlank(apiReq.getBody().getNickname())){
                            apiResp.setMsg("请填写用户姓名");
                            return apiResp;
                        }
                    }

                    user = new User();
                    user.setNickname(apiReq.getBody().getNickname());
                    user.setPhone(apiReq.getBody().getPhone());

                    Clerk clerk = new Clerk();
                    clerk.setMerchantUserId(loginUser.getId());
                    clerk.setNote(apiReq.getBody().getNote());

                    try {
                        if(ClerkService.self().add(clerk,user)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/merchant/clerk/info.data")
    public ClerkUserInfoResponse info(HttpServletRequest request) {
    	ClerkUserInfoResponse apiResp = new ClerkUserInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	ClerkUserInfoRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserInfoRequest.class);
        if(apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                Clerk clerk = ClerkService.self().getJoinByKeys(apiReq.getBody().getUserId(),loginUser.getId());
                if (clerk != null) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setUserId(clerk.getUserId());
                    apiResp.getBody().setUserName(clerk.getUser().getName());
                    apiResp.getBody().setUserPhone(clerk.getUser().getPhone());
                    if(StringTools.isNotBlank(clerk.getUser().getFaceImg())){
                    	 String resDomain = WebConstants.getResDomain(request);
                        apiResp.getBody().setUserFaceImg(WebUtils.setHttpDomain(resDomain,clerk.getUser().getFaceImg()));
                    }
                    apiResp.getBody().setCanCancelOrder(clerk.getCanCancelOrder());
                    apiResp.getBody().setNote(clerk.getNote());
                    apiResp.getBody().setLastLoginDate(clerk.getLastLoginDate());
                    apiResp.getBody().setCreateDate(clerk.getCreateDate());
                    apiResp.getBody().setPlaceCount(0);

                    Long placeCount = PlaceClerkService.self().countByUserKeys(clerk.getUserId(),loginUser.getId());
                    if (placeCount != null) {
                        apiResp.getBody().setPlaceCount(placeCount.intValue());
                    }

                    List<ClerkFuncModel> funcModelList = ClerkFuncModelService.self().findJoinByUserKeys(clerk.getUserId(),loginUser.getId());
                    if (funcModelList != null && funcModelList.size() > 0) {
                        apiResp.getBody().setFuncModelItems(new ArrayList<>());
                        for (ClerkFuncModel funcModel : funcModelList) {
                        	ClerkUserInfoResponse.FuncModelItem item = new ClerkUserInfoResponse.FuncModelItem();
                            item.setId(funcModel.getFuncModel().getId());
                            item.setName(funcModel.getFuncModel().getName());
                            item.setIconImg(funcModel.getFuncModel().getIconUrl());
                            item.setState(funcModel.getState());
                            apiResp.getBody().getFuncModelItems().add(item);
                        }
                    }
                }else{
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return apiResp;
    }
   
    @Route(value = "/agent/api/v1/merchant/clerk/place/physical_store/list.data")
    public ClerkUserPlaceListResponse placeList(HttpServletRequest request) {
    	ClerkUserPlaceListResponse apiResp = new ClerkUserPlaceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	ClerkUserPlaceListRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserPlaceListRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                List<PlaceClerk> placeClerkList = PlaceClerkService.self().findByUserKeys(apiReq.getBody().getUserId(),loginUser.getId());
                if(placeClerkList != null && placeClerkList.size() > 0){
                    List<Long> placeIds = new ArrayList<>();
                    for(PlaceClerk placeClerk : placeClerkList){
                        placeIds.add(placeClerk.getPlaceId());
                    }

                    Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();

                    PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
                    search.setName(apiReq.getBody().getTrim());
                    search.setPlaceIds(placeIds);
                    List<PlacePhysicalStore> data = PlacePhysicalStoreService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                    if (data != null && data.size() > 0) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setItems(new ArrayList<>());

                        String resDomain = WebConstants.getResDomain(request);
                        for (PlacePhysicalStore place : data) {
                        	ClerkUserPlaceListResponse.Item item = new ClerkUserPlaceListResponse.Item();
                            item.setId(place.getId());
                            item.setName(place.getName());
                            item.setProvince(place.getProvince());
                            item.setCity(place.getCity());
                            item.setCityArea(place.getCityArea());
                            if (StringTools.isNotBlank(place.getThumbnailImg())) {
                                item.setImgUrl(resDomain + place.getThumbnailImg());
                            }

                            for(PlaceClerk placeClerk : placeClerkList){
                                if(placeClerk.getPlaceId().equals(item.getId())){
                                    item.setJoinDate(placeClerk.getCreateDate());
                                }
                            }
                            apiResp.getBody().getItems().add(item);
                        }
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/merchant/clerk/func_model/list.data")
    public ClerkUserFuncModelListResponse funcModelList(HttpServletRequest request) {
    	ClerkUserFuncModelListResponse apiResp = new ClerkUserFuncModelListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	ClerkUserFuncModelListRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserFuncModelListRequest.class);
        if(apiReq != null && apiReq.getBody().getUserId() != null) {
	        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
	        if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
	        	List<ClerkUserFuncModelListResponse.Item> items = new ArrayList<>();
	          
	        	List<ClerkFuncModel> clerkFuncModelList = ClerkFuncModelService.self().findByUserKeys(apiReq.getBody().getUserId(),loginUser.getId());
	        	
	        	List<FuncModel> funcModelList = FuncModelService.self().findByType(FuncModelEnum.Type.Dealer.index());
           	 	List<AgentRelationFuncModel> arFuncModelList = AgentRelationFuncModelService.self().findJoinByUserKeys(loginUser.getParentId(), loginUser.getId());
	           	if (funcModelList != null && funcModelList.size() > 0) {
	           		for (FuncModel funcModel : funcModelList) {
	           			boolean flag = false;
	           			if(FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
	           				flag = true;
	           				for (AgentRelationFuncModel relationFuncModel : arFuncModelList) {
	           					if(relationFuncModel.getFuncModelId().equals(funcModel.getId())) {
		           					if(AgentRelationFuncModelEnum.State.Close.index().equals(relationFuncModel.getState())){
		           						flag = false;
		           					}
		           					break;
	           					}
	           				}
	           			}else {
	           				for (AgentRelationFuncModel relationFuncModel : arFuncModelList) {
	           					if(relationFuncModel.getFuncModelId().equals(funcModel.getId())) {
		           					if(AgentRelationFuncModelEnum.State.Open.index().equals(relationFuncModel.getState())){
		           						flag = true;
		           					}
		           					break;
	           					}
	           				}
	           			}
	           			
	           			if(flag) {
	           				ClerkUserFuncModelListResponse.Item item = new ClerkUserFuncModelListResponse.Item();
                            item.setId(funcModel.getId());
                            item.setName(funcModel.getName());
                            item.setIconImg(funcModel.getIconUrl());
                            item.setUrl(funcModel.getUrl());
                            item.setState(ClerkFuncModelEnum.State.Close.index());
                            if(clerkFuncModelList != null && clerkFuncModelList.size() > 0) {
                           	 for(ClerkFuncModel clerkFuncModel : clerkFuncModelList) {
                           		 if(clerkFuncModel.getFuncModelId().equals(item.getId())) {
                           			 item.setState(clerkFuncModel.getState());
                           			 break;
                           		 }
                           	 }
                            }
                            item.setHomeShow(EFuncModelShowState.HomeShow.index());
                            items.add(item);
	           			}
	           		}
	            }
	  
	            if (items.size() > 0) {
	                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                apiResp.getBody().setItems(items);
	            }
	        }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/merchant/clerk/func_model/update.do")
    public DefaultAPIResponse updateFuncModel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        ClerkUserFuncModelUpdateRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserFuncModelUpdateRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && apiReq.getBody().getFuncModelId() != null && apiReq.getBody().getState() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                Clerk clerk = ClerkService.self().getJoinByKeys(apiReq.getBody().getUserId(),loginUser.getId());
                if(clerk == null){
                    apiResp.setMsg("未找到店员信息");
                    return apiResp;
                }
                
                FuncModel funcModel = null;
                
                AgentRelationFuncModel agentRelationFuncModel = AgentRelationFuncModelService.self().getJoinByKeys(loginUser.getParentId()
                		, loginUser.getId(), apiReq.getBody().getFuncModelId());
                if(agentRelationFuncModel != null){
                	if(AgentRelationFuncModelEnum.State.Close.index().equals(agentRelationFuncModel.getState())) {
	                	apiResp.setMsg("无权限设置此功能模块");
	                    return apiResp;
	                }
                	funcModel = agentRelationFuncModel.getFuncModel();
                }else {
	                funcModel = FuncModelService.self().getById(apiReq.getBody().getFuncModelId());
	                if(funcModel == null || !FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
	                	apiResp.setMsg("无权限设置此功能模块");
	                    return apiResp;
	                }
                }

                if(apiReq.getBody().getState() == 2) {
                	//开启
                	try {
                        if (ClerkFuncModelService.self().open(clerk.getUserId(),loginUser.getId(), apiReq.getBody().getFuncModelId())){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
                	//关闭
                	 ClerkFuncModel clerkFuncModel = ClerkFuncModelService.self().getJoinByKeys(clerk.getUserId(),loginUser.getId()
                     		, apiReq.getBody().getFuncModelId());
                	 if(clerkFuncModel != null) {
                		//直接删除
             			try {
                			if(ClerkFuncModelService.self().deleteByKeys(clerk.getUserId(),loginUser.getId()
                             		, apiReq.getBody().getFuncModelId())) {
                				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                			}
             			} catch (LogicException e) {
                             apiResp.setMsg(e.getMessage());
                         }
                	 }else {
                		 apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	 }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/merchant/clerk/power/update.do")
    public DefaultAPIResponse updatePoer(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        ClerkUserPowerUpdateRequest apiReq = WebUtils.getJsonRequest(request, ClerkUserPowerUpdateRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && StringTools.isNotBlank(apiReq.getBody().getType()) && apiReq.getBody().getState() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                Clerk clerk = ClerkService.self().getJoinByKeys(apiReq.getBody().getUserId(),loginUser.getId());
                if(clerk == null){
                    apiResp.setMsg("未找到店员信息");
                    return apiResp;
                }
                
                if("canCancelOrder".equals(apiReq.getBody().getType())) {
                	if(ClerkService.self().updateCanCancelOrder(clerk.getUserId(),loginUser.getId(),apiReq.getBody().getState())) {
                		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	}
                }else {
                	apiResp.setMsg("无效的权限类型");
                    return apiResp;
                }
            }
        }
        return apiResp;
    }
}
